﻿namespace clowncar
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Reflection;

    class Program
    {
        static int Main(string[] args)
        {
            var exeFile = System.AppDomain.CurrentDomain.FriendlyName;
            var clownFile = Path.GetFileNameWithoutExtension(exeFile) + ".clown";

            //Look in me.clown
            if (File.Exists(clownFile)){

                //rename myself.
                File.Move(exeFile, exeFile + "." + DateTime.Now.ToString("yyyyMMddHHmmss"));
                
                var clownCode = File.ReadAllText(clownFile);
                var updater = "GrabAndRun.exe";
                var tempFolder = Path.GetTempPath();
                var target = AssemblyUtils.ExtractResource(updater, tempFolder);
                
                var psi = new ProcessStartInfo();
                psi.UseShellExecute = false;
                psi.RedirectStandardOutput = false;
                string url = clownCode;
                string path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                var exeToRun = exeFile;

                //call grabandrun.exe with appropriate config.
                psi.Arguments = string.Format(" --url=\"{0}\" --path=\"{1}\" --exec=\"{2}\" --args=\"{3}\"", url, path, exeToRun, string.Join(" ", args));
                Console.WriteLine(psi.Arguments);
                
                psi.FileName = target; 
                
               var  p = Process.Start(psi);
               p.WaitForExit();
            }

            return 0;
        }
    }
}
